#include <iostream>
#include <boost/foreach.hpp>

#include "melon/client/thrift_client_pool.h"
#include "RecentContactService.h"

using imserver::RecentContactServiceClient;
using imserver::RecentContact;
using imserver::RecentContactList;
using melon::client::ClientPool;

void * ThreadFun(void * data) {
  ClientPool<RecentContactServiceClient> * pool = (ClientPool<RecentContactServiceClient>*)data;

  // const char * addrs[] = {"127.0.0.1:9091", "127.0.0.1:9093"};
  const char * addrs[] = {"127.0.0.1:9092"};
  int addr_count = sizeof(addrs) / sizeof(char*);
  RecentContactServiceClient * client = NULL;

  for (int i = 0; i < 20; ++i) {
    // for (int i = 0; i < 1; ++i) {
    std::string addr(addrs[i % addr_count]);
    client = pool->Alloc(addr);
    if (!client) {
      continue;
    }

    bool success = true;
    try {
      RecentContactList cell;
      client->GetFavorites(cell, 10001, 0, 20);
      std::cout << "==================G e t C o n t a c t s=================" << std::endl;
      BOOST_FOREACH(const RecentContact& contact, cell) {
        std::cout << contact.uid << " | " << contact.remark << std::endl;
      }

      std::cout << std::endl;
      std::cout << "==================A       d           d=================" << std::endl;
      client->AddFavorite(10001, 10002+i);
      if (i % 5 == 0) 
        client->UpdateRemark(10001, 10002+i, "testtttaads");
      if (i % 10 == 0) 
        ;//client->RemoveFavorite(10001, 10002+i);

    } catch (const std::exception & e) {
      std::cout << addr << " error:" << e.what() << std::endl;
      success = false;
    }
    pool->Release(addr, client, success);
  }
  return NULL;
  }

  const int kThreadCount = 1;

  int main() {
    LOG_INIT("./recent_contact_test.log", "WARN");
    ClientPool<RecentContactServiceClient> pool;

    pthread_t ts[kThreadCount];

    for (int i = 0; i < kThreadCount; ++i) {
      pthread_create(&ts[i], NULL, ThreadFun, &pool);
    }

    for (int i = 0; i < kThreadCount; ++i) {
      pthread_join(ts[i], NULL);
    }
    return 0;
  }

